package gov.pr.celepar.sentinela.admin.action;

import java.util.Collection;

import gov.pr.celepar.sentinela.admin.dao.SistemaDAO;
import gov.pr.celepar.sentinela.admin.dao.factory.DAOFactoryServer;
import gov.pr.celepar.sentinela.admin.excecao.SentinelaServerException;
import gov.pr.celepar.sentinela.admin.form.OperacaoForm;
import gov.pr.celepar.sentinela.admin.pojo.Operacao;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;

public class OperacaoAction extends BaseAction {

	private static Log logger = LogFactory.getLog(OperacaoAction.class);

	public String executar(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws SentinelaServerException, Exception {

		OperacaoForm operacaoForm = (OperacaoForm) form;

		this.listarSistemasAutorizados(request);

		if (this.CONF_INCLUIR.equalsIgnoreCase(operacaoForm.getAcao())) {
			this.comunicacao.autorizaOperacao('I', request, response);
			incluir(operacaoForm);

		} else if (this.CONF_EXCLUIR.equalsIgnoreCase(operacaoForm.getAcao())) {
			this.comunicacao.autorizaOperacao('E', request, response);
			excluir(operacaoForm);

		}
		consultar(operacaoForm, request);

		return "lista_operacoes";
	}

	private void incluir(OperacaoForm form) {
		Operacao o = new Operacao();
		o.setCodSistema(Long.decode(form.getCodSistema()));
		o.setNome(form.getNome());
		o.setTipo(form.getTipo().charAt(0));
		try {
			DAOFactoryServer daoFactory = DAOFactoryServer.getDAOFactory();
			SistemaDAO sistemaB = daoFactory.getSistemaDAO();

			sistemaB.incluirOperacao(o);
		} catch (Exception e) {
			logger.error("", e);
		}
	}

	private void excluir(OperacaoForm form) {
		String[] cods = form.getCodOperacao();

		if (cods != null) {
			for (int i = 0; i < cods.length; i++) {

				Operacao o = new Operacao();
				o.setCodSistema(Long.decode(form.getCodSistema()));
				o.setTipo(cods[i].charAt(0));
				try {
					DAOFactoryServer daoFactory = DAOFactoryServer
							.getDAOFactory();
					SistemaDAO sistemaB = daoFactory.getSistemaDAO();

					sistemaB.excluirOperacao(o);
				} catch (Exception e) {
					logger.error("", e);
				}
			}
		}
	}

	private void consultar(OperacaoForm form, HttpServletRequest request) {
		if (form.getCodSistema() != null && !form.getCodSistema().equals("")) {
			try {
				DAOFactoryServer daoFactory = DAOFactoryServer.getDAOFactory();
				SistemaDAO sistemaB = daoFactory.getSistemaDAO();

				Collection c = sistemaB.getOperacoesSistemas(Long.decode(form
						.getCodSistema()));
				request.setAttribute("listaOperacoes", c);

			} catch (Exception e) {
				logger.error("", e);
			}
		}
	}
}
